import mqttClient from './mqttClient';
import { useDeviceStore } from '../stores/deviceStore';

// 设备状态主题前缀
const DEVICE_STATUS_TOPIC_PREFIX = 'device/status/';

// 初始化MQTT设备状态管理器
const initDeviceStatusManager = () => {
  const deviceStore = useDeviceStore();
  
  // 订阅所有设备状态主题
  mqttClient.subscribe(`${DEVICE_STATUS_TOPIC_PREFIX}#`);
  
  // 监听设备状态消息
  mqttClient.on('message', (topic, message) => {
    // 检查是否是设备状态主题
    if (topic.startsWith(DEVICE_STATUS_TOPIC_PREFIX)) {
      try {
        // 从主题中提取设备ID
        const deviceId = topic.substring(DEVICE_STATUS_TOPIC_PREFIX.length);
        
        // 解析消息内容
        const statusData = JSON.parse(message.toString());
        
        // 更新当前设备状态（如果是当前选中的设备）
        if (deviceStore.currentDevice && deviceStore.currentDevice.id === parseInt(deviceId)) {
          const updatedDevice = {
            ...deviceStore.currentDevice,
            onlineStatus: statusData.online ? '上线' : '下线',
            runningStatus: statusData.running ? '运行' : '停止',
            faultStatus: statusData.fault ? '故障' : '正常',
            auth: statusData.auth || (statusData.online ? '上线' : '下线') // 添加auth字段，如果没有则使用online状态
          };
          
          // 更新当前设备状态
          deviceStore.setCurrentDevice(updatedDevice);
          
          console.log(`当前设备 ${deviceId} 状态已更新:`, statusData);
        }
      } catch (error) {
        console.error('处理设备状态消息错误:', error);
      }
    }
  });
  
  // 监听MQTT连接状态
  mqttClient.on('connect', () => {
    console.log('MQTT连接成功，开始监听设备状态');
  });
  
  mqttClient.on('error', (err) => {
    console.error('MQTT连接错误:', err);
  });
  
  mqttClient.on('offline', () => {
    console.log('MQTT客户端离线，设备状态更新暂停');
  });
  
  return {
    // 手动更新设备状态的方法
    updateDeviceStatus: (deviceId, status) => {
      const topic = `${DEVICE_STATUS_TOPIC_PREFIX}${deviceId}`;
      mqttClient.publish(topic, JSON.stringify(status));
    },
    
    // 请求设备状态更新
    requestDeviceStatus: (deviceId) => {
      const requestTopic = `device/request/${deviceId}`;
      mqttClient.publish(requestTopic, JSON.stringify({ action: 'getStatus' }));
    }
  };
};

export default initDeviceStatusManager;